package com.smugmugsoftware.airconcalc.advanced;

import java.util.Iterator;
import java.util.Vector;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.LinearGradient;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class AdvancedReportFragment extends Fragment {

	private SharedPreferences prefs;
	private MainActivityInterface activity;
	private Building thisBuilding;

	private View thisView;
	private boolean useTons;
	private boolean cancelThread;
	private LinearLayout reportWindow;
	private Thread reportThread;

	public AdvancedReportFragment() {}

	public AdvancedReportFragment(Building building) {
		thisBuilding = building;
		thisBuilding.attachChildren();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		prefs = getActivity().getSharedPreferences("config.dat", Context.MODE_PRIVATE);
		useTons = prefs.getBoolean("USE_TONS", false);
		cancelThread = false;

		setRetainInstance(true);

		if (savedInstanceState != null && savedInstanceState.getParcelable("SAVED_BUILDING") != null) {
			thisBuilding = savedInstanceState.getParcelable("SAVED_BUILDING");
			thisBuilding.attachChildren();
		}

		prefs = getActivity().getSharedPreferences("config.dat", Context.MODE_PRIVATE);
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			this.activity = (MainActivityInterface) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString() + " must implement OnHeadlineSelectedListener");
		}
	}

	@Override
	public View onCreateView(final LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {

		thisView = inflater.inflate(R.layout.advanced_report_fragment, container, false);
		
		activity.displayInfoDialog(thisView.getContext(), InformationDialog.REPORT_FIRST_RUN, "REPORT_FIRST_RUN");

		final TableParser parser = new TableParser(thisView.getContext(), R.raw.heatgain);
		final int column = getColumnNumber(thisBuilding.getLocaleData());
		final int windowColumn = getWindowColumnNumber(thisBuilding.getLocaleData());

		reportWindow = (LinearLayout) thisView.findViewById(R.id.report_window);

		reportThread = new Thread(new Runnable() {

			public void run() {

				View reportListView = null;

				Iterator<Room> roomIterator = thisBuilding.getRooms().iterator();
				Room thisRoom = null;
				Wall thisWall = null;
				WindowDoor thisWindowDoor = null;
				CeilingFloor thisCeilingFloor = null;
				SensibleLoad thisSensibleLoad = null;

				Iterator<Wall> wallIterator = null;

				Iterator<WindowDoor> winDoorIterator = null;
				Vector<WindowDoor> windowVector = new Vector<WindowDoor>();
				Vector<WindowDoor> doorVector = new Vector<WindowDoor>();
				Iterator<WindowDoor> windowIterator = null;
				Iterator<WindowDoor> doorIterator = null;

				Iterator<CeilingFloor> celFloorIterator = null;
				Vector<CeilingFloor> ceilingVector = new Vector<CeilingFloor>();
				Vector<CeilingFloor> floorVector = new Vector<CeilingFloor>();
				Iterator<CeilingFloor> ceilingIterator = null;
				Iterator<CeilingFloor> floorIterator = null;

				Iterator<SensibleLoad> sensibleIterator = null;

				int thisWallArea = 0;
				double thisWallBTU = 0;
				double wallBTUMultiplier;

				int thisWindowUnshadedArea = 0;
				int thisWindowShadedArea = 0;
				int totalWindowBTU = 0;
				double thisWindowBTU = 0;
				double windowBTUMultiplier = 0;
				String shadeString = "";
				char newChar = ' ';

				double thisDoorArea = 0;
				double thisDoorBTU = 0;
				int totalDoorBTU = 0;
				double doorBTUMultiplier = 0;

				double ceilingFloorBTUMultiplier = 0;

				while (roomIterator.hasNext()) {
					thisRoom = roomIterator.next();

					windowVector = new Vector<WindowDoor>();
					doorVector = new Vector<WindowDoor>();
					ceilingVector = new Vector<CeilingFloor>();
					floorVector = new Vector<CeilingFloor>();

					reportListView = inflater.inflate(R.layout.report_heading_list_item, container, false);		
					((TextView) reportListView.findViewById(R.id.ID_label)).setText(thisRoom.getName());
					//			reportWindow.addView(reportListView);
					addToList(reportListView);
					if (cancelThread) {
						return;
					}

					wallIterator = thisRoom.getWalls().iterator();
					winDoorIterator= thisRoom.getWindowsDoors().iterator();
					while (winDoorIterator.hasNext()) {
						thisWindowDoor = winDoorIterator.next();

						if (thisWindowDoor.isAWindow()) {
							windowVector.add(thisWindowDoor);
						} else if (!thisWindowDoor.isAWindow()) {
							doorVector.add(thisWindowDoor);
						}
					}
					windowIterator = windowVector.iterator();
					doorIterator = doorVector.iterator();

					celFloorIterator = thisRoom.getCeilingsFloors().iterator();
					while (celFloorIterator.hasNext()) {
						thisCeilingFloor = celFloorIterator.next();

						if (thisCeilingFloor.isACeiling()) {
							ceilingVector.add(thisCeilingFloor);
						} else if (!thisCeilingFloor.isACeiling()) {
							floorVector.add(thisCeilingFloor);
						}
					}
					ceilingIterator = ceilingVector.iterator();
					floorIterator = floorVector.iterator();

					sensibleIterator = thisRoom.getSensibleLoads().iterator();

					while (wallIterator.hasNext()) {
						thisWall = wallIterator.next();
						reportListView = inflater.inflate(R.layout.report_wall_list_item, container, false);

						((TextView) reportListView.findViewById(R.id.ID)).setText(String.valueOf(thisWall.getID()));
						((TextView) reportListView.findViewById(R.id.facing)).setText(thisWall.getLongFacingString());
						((TextView) reportListView.findViewById(R.id.dimension)).setText(thisWall.getLengthString() + " x " + thisWall.getWidthString());
						((TextView) reportListView.findViewById(R.id.area)).setText(thisWall.getAreaString());

						thisWallArea = (int) thisWall.getArea();
						wallBTUMultiplier = Double.parseDouble(parser.getDataPoint(thisWall.getConstructionNumber(), "Walls", column));

						for (WindowDoor checkWindowDoor : windowVector) {
							if (checkWindowDoor.getFacing() == thisWall.getFacing()) {
								thisWallArea = (int) (thisWallArea - checkWindowDoor.getAreaInFeet());
							}
						}

						thisWallBTU = thisWallArea * wallBTUMultiplier;

						((TextView) reportListView.findViewById(R.id.btu)).setText(String.valueOf((int) thisWallBTU));

						//				reportWindow.addView(reportListView);
						addToList(reportListView);
						if (cancelThread) {
							return;
						}
					}

					while (windowIterator.hasNext()) {
						thisWindowDoor = windowIterator.next();
						thisWindowBTU = 0;

						reportListView = inflater.inflate(R.layout.report_window_list_item, container, false);

						((TextView) reportListView.findViewById(R.id.ID)).setText(String.valueOf(windowVector.indexOf(thisWindowDoor) + 1));
						((TextView) reportListView.findViewById(R.id.facing)).setText(thisWindowDoor.getLongFacingString());
						((TextView) reportListView.findViewById(R.id.type)).setText(thisWindowDoor.getWindowTypeString());
						((TextView) reportListView.findViewById(R.id.area)).setText(String.valueOf((int) thisWindowDoor.getAreaInFeet()));
						((TextView) reportListView.findViewById(R.id.shade)).setText(String.valueOf((int) thisWindowDoor.getShadedAreaInFeet()));
						((TextView) reportListView.findViewById(R.id.shade_percent))
						.setText(String.valueOf((int) (100 * thisWindowDoor.getShadedAreaInFeet() / thisWindowDoor.getAreaInFeet())));

						thisWindowUnshadedArea = (int) (thisWindowDoor.getAreaInFeet() - thisWindowDoor.getShadedAreaInFeet());
						thisWindowShadedArea = (int) thisWindowDoor.getShadedAreaInFeet();

						if (thisWindowShadedArea > 0) {

							for (int i = 0; i < thisWindowDoor.getConstructionNumber().length(); i++) {
								newChar = thisWindowDoor.getConstructionNumber().charAt(i);

								if (i == 1) {
									newChar = 'A';
								}

								if (i == 4) {
									newChar = 'a';
								}

								shadeString = shadeString + newChar;
							}

							shadeString = shadeString + "-A";

							windowBTUMultiplier = Double.parseDouble(parser.getDataPoint(shadeString, "Windows & Doors", windowColumn));
							thisWindowBTU = thisWindowBTU + (thisWindowShadedArea * windowBTUMultiplier); 
							shadeString = "";
						}

						windowBTUMultiplier = Double.parseDouble(parser.getDataPoint(thisWindowDoor.getConstructionNumber() 
								+ "-" + thisWindowDoor.getFacingString(), "Windows & Doors", windowColumn));
						thisWindowBTU = thisWindowBTU + (thisWindowUnshadedArea * windowBTUMultiplier);
						totalWindowBTU = (int) (thisWindowBTU * thisWindowDoor.getQty());

						((TextView) reportListView.findViewById(R.id.btu)).setText(String.valueOf((int) thisWindowBTU));
						((TextView) reportListView.findViewById(R.id.btu_quantity)).setText(String.valueOf(thisWindowDoor.getQty()));
						((TextView) reportListView.findViewById(R.id.btu_total)).setText(String.valueOf(totalWindowBTU));

						addToList(reportListView);
						if (cancelThread) {
							return;
						}
					}

					while (doorIterator.hasNext()) {
						thisWindowDoor = doorIterator.next();

						reportListView = inflater.inflate(R.layout.report_door_list_item, container, false);

						((TextView) reportListView.findViewById(R.id.ID)).setText(String.valueOf(doorVector.indexOf(thisWindowDoor) + 1));
						((TextView) reportListView.findViewById(R.id.facing)).setText(thisWindowDoor.getLongFacingString());
						((TextView) reportListView.findViewById(R.id.area)).setText(String.valueOf((int) thisWindowDoor.getAreaInFeet()));

						thisDoorArea = thisWindowDoor.getAreaInFeet();

						windowBTUMultiplier = Double.parseDouble(parser.getDataPoint(thisWindowDoor.getConstructionNumber(), "Windows & Doors", column));
//						doorBTUMultiplier = Double.parseDouble(parser.getDataPoint(thisWindowDoor.getConstructionNumber() 
//								+ "-" + thisWindowDoor.getFacingString(), "Windows & Doors", windowColumn));
						thisDoorBTU = thisDoorArea * doorBTUMultiplier;
						totalDoorBTU = (int) (thisDoorBTU * thisWindowDoor.getQty());

						((TextView) reportListView.findViewById(R.id.btu)).setText(String.valueOf((int) thisDoorBTU));
						((TextView) reportListView.findViewById(R.id.btu_quantity)).setText(String.valueOf(thisWindowDoor.getQty()));
						((TextView) reportListView.findViewById(R.id.btu_total)).setText(String.valueOf(totalDoorBTU));

						addToList(reportListView);
						if (cancelThread) {
							return;
						}
					}

					while (ceilingIterator.hasNext()) {
						thisCeilingFloor = ceilingIterator.next();

						reportListView = inflater.inflate(R.layout.report_celfloor_list_item, container, false);

						((TextView) reportListView.findViewById(R.id.ID_label)).setText(String.valueOf(thisCeilingFloor.getTypeString()));
						((TextView) reportListView.findViewById(R.id.ID)).setText(String.valueOf(ceilingVector.indexOf(thisCeilingFloor) + 1));
						((TextView) reportListView.findViewById(R.id.type)).setText(thisCeilingFloor.getCeilingTypeString());
						((TextView) reportListView.findViewById(R.id.area)).setText(String.valueOf((int) thisCeilingFloor.getArea()));

						ceilingFloorBTUMultiplier = Double.parseDouble(parser.getDataPoint(thisCeilingFloor.getConstructionNumber(), "Ceilings & Floors", column));

						((TextView) reportListView.findViewById(R.id.btu)).setText(String.valueOf((int) (thisCeilingFloor.getArea() * ceilingFloorBTUMultiplier)));

						addToList(reportListView);
						if (cancelThread) {
							return;
						}
					}

					while (floorIterator.hasNext()) {
						thisCeilingFloor = floorIterator.next();

						reportListView = inflater.inflate(R.layout.report_celfloor_list_item, container, false);

						((TextView) reportListView.findViewById(R.id.ID_label)).setText(String.valueOf(thisCeilingFloor.getTypeString()));
						((TextView) reportListView.findViewById(R.id.ID)).setText(String.valueOf(floorVector.indexOf(thisCeilingFloor) + 1));
						((TextView) reportListView.findViewById(R.id.type)).setText(thisCeilingFloor.getCeilingTypeString());
						((TextView) reportListView.findViewById(R.id.area)).setText(String.valueOf((int) thisCeilingFloor.getArea()));

						ceilingFloorBTUMultiplier = Double.parseDouble(parser.getDataPoint(thisCeilingFloor.getConstructionNumber(), "Ceilings & Floors", column));

						((TextView) reportListView.findViewById(R.id.btu)).setText(String.valueOf((int) (thisCeilingFloor.getArea() * ceilingFloorBTUMultiplier)));

						addToList(reportListView);
						if (cancelThread) {
							return;
						}
					}

					while (sensibleIterator.hasNext()) {
						thisSensibleLoad = sensibleIterator.next();

						reportListView = inflater.inflate(R.layout.report_sensible_list_item, container, false);

						((TextView) reportListView.findViewById(R.id.ID)).setText(String.valueOf(thisSensibleLoad.getID()));
						((TextView) reportListView.findViewById(R.id.name)).setText(thisSensibleLoad.getName());

						if (thisSensibleLoad.getLoadDescriptorString().length() > 1) {
							((TextView) reportListView.findViewById(R.id.load)).setText(thisSensibleLoad.getLoadDescriptorString());
						} else {
							((TextView) reportListView.findViewById(R.id.load)).setVisibility(View.GONE);
						}

						((TextView) reportListView.findViewById(R.id.btu)).setText(String.valueOf(thisSensibleLoad.getBtu()));
						((TextView) reportListView.findViewById(R.id.btu_quantity)).setText(String.valueOf(thisSensibleLoad.getQty()));
						((TextView) reportListView.findViewById(R.id.btu_total)).setText(String.valueOf(thisSensibleLoad.getBtu() * thisSensibleLoad.getQty()));

						addToList(reportListView);
						if (cancelThread) {
							return;
						}
					}

					if (thisRoom.getWalls().size() + thisRoom.getWindowsDoors().size() + thisRoom.getCeilingsFloors().size() + thisRoom.getSensibleLoads().size() > 0) {
						reportListView = inflater.inflate(R.layout.report_subtotal_list_item, container, false);

						((TextView) reportListView.findViewById(R.id.btu)).setText(String.valueOf(thisRoom.getTotalRoomLoad(thisView.getContext())));

						addToList(reportListView);
						if (cancelThread) {
							return;
						}
					}
				}

				reportListView = inflater.inflate(R.layout.report_infiltration_list_item, container, false);
				((TextView) reportListView.findViewById(R.id.cfm)).setText(String.valueOf((int) thisBuilding.getInfiltrationCFM()));
				((TextView) reportListView.findViewById(R.id.btu)).setText(String.valueOf((int) thisBuilding.getInfiltrationBTU()));
				addToList(reportListView);

				reportListView = inflater.inflate(R.layout.report_total_list_item, container, false);
				((TextView) reportListView.findViewById(R.id.btu)).setText(String.valueOf((int) thisBuilding.getTotalBuildingLoad(thisView.getContext())));
				addToList(reportListView);
			}
		});
		reportThread.start();

		ImageView cancelButton = (ImageView) thisView.findViewById(R.id.cancel_button);
		cancelButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				activity.closeReport();
			}
		});

		if (thisView.findViewById(R.id.localeLabelWrapper) != null) {
			TextView installer = (TextView) thisView.findViewById(R.id.installer);
			TextView address = (TextView) thisView.findViewById(R.id.address);
			TextView locale = (TextView) thisView.findViewById(R.id.locale);
			TextView latitude = (TextView) thisView.findViewById(R.id.latitude);
			TextView latitudeNS = (TextView) thisView.findViewById(R.id.latitude_unit_label);
			TextView designTemp = (TextView) thisView.findViewById(R.id.internal);
			TextView externalTemp = (TextView) thisView.findViewById(R.id.external);
			TextView dailyRange = (TextView) thisView.findViewById(R.id.daily_range);
			TextView constTightness = (TextView) thisView.findViewById(R.id.tightness);

			if (thisBuilding.getEstimatorName().length() > 16 && thisBuilding.getEstimatorName().length() <= 26) {
				installer.setTextSize(12);
				installer.setText(thisBuilding.getEstimatorName());
			} else if (thisBuilding.getEstimatorName().length() > 26) {
				installer.setTextSize(12);
				installer.setText(thisBuilding.getEstimatorName().substring(0, 23) + "...");
			} else {
				installer.setTextSize(14);
				installer.setText(thisBuilding.getEstimatorName());
			}

			if (thisBuilding.getAddress().length() > 20 && thisBuilding.getAddress().length() <= 30) {
				address.setTextSize(12);
				address.setText(thisBuilding.getAddress());
			} else if (thisBuilding.getAddress().length() > 30) {
				address.setTextSize(12);
				address.setText(thisBuilding.getAddress().substring(0, 26) + "...");
			} else {
				address.setTextSize(14);
				address.setText(thisBuilding.getAddress());
			}

			locale.setText(thisBuilding.getLocaleName());
			designTemp.setText(String.valueOf(thisBuilding.getInternalTemp()));
			externalTemp.setText(String.valueOf(thisBuilding.getExternalDryBulb()));
			dailyRange.setText(String.valueOf(thisBuilding.getDailyRangeInt()));
			constTightness.setText(thisBuilding.getConstrutionTightnessString());

			int thisLatitude = thisBuilding.getActualLatitude();
			if (thisLatitude <= 0) {
				thisLatitude = thisLatitude * -1;
				latitudeNS.setText("S");
			} else {
				latitudeNS.setText("N");
			}

			latitude.setText(String.valueOf(thisLatitude));
		}

		return thisView;
	}


	private int getColumnNumber(int[] localeData) {

		if (localeData[0] <= 12) {
			if (localeData[1] == Building.RANGE_LOW) {
				return 1;
			} else if (localeData[1] == Building.RANGE_MEDIUM || localeData[1] == Building.RANGE_HIGH) {
				return 2;
			}
		} else if (localeData[0] > 12 && localeData[0] <= 17) {
			if (localeData[1] == Building.RANGE_LOW) {
				return 3;
			} else if (localeData[1] == Building.RANGE_MEDIUM) {
				return 4;
			} else if (localeData[1] == Building.RANGE_HIGH) {
				return 5;
			}
		} else if (localeData[0] > 17 && localeData[0] <= 22) {
			if (localeData[1] == Building.RANGE_LOW) {
				return 6;
			} else if (localeData[1] == Building.RANGE_MEDIUM) {
				return 7;
			} else if (localeData[1] == Building.RANGE_HIGH) {
				return 8;
			}
		} else if (localeData[0] > 22 && localeData[0] <= 27) {
			if (localeData[1] == Building.RANGE_LOW || localeData[1] == Building.RANGE_MEDIUM) {
				return 9;
			} else if (localeData[1] == Building.RANGE_HIGH) {
				return 10;
			}
		} else if (localeData[0] > 27 && localeData[0] <= 32) {
			return 11;
		} else if (localeData[0] > 32) {
			return 12;
		}

		return 0;
	}

	private int getWindowColumnNumber(int[] localeData) {
		if (localeData[0] <= 12) {
			return 1;
		} else if (localeData[0] > 12 && localeData[0] <= 17) {
			return 2;
		} else if (localeData[0] > 17 && localeData[0] <= 22) {
			return 3;
		} else if (localeData[0] > 22 && localeData[0] <= 27) {
			return 4;
		} else if (localeData[0] > 27 && localeData[0] <= 32) {
			return 5;
		} else if (localeData[0] > 32) {
			return 6;
		}

		return 0;
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

		outState.putParcelable("SAVED_BUILDING", thisBuilding);
	}

	protected void addToList(final View view)	 {
		if (!cancelThread) {
			getActivity().runOnUiThread(new Runnable() {

				public void run() {
					AdvancedReportFragment.this.reportWindow.addView(view);
				}
			});
		}
	}

	@Override
	public void onStop() {
		super.onStop();

		if (reportThread != null && reportThread.isAlive()) {
			cancelThread = true;
		}
	}
}